package org.an.demo.util;

import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by an on 2016/11/5.<br/>
 * 数据解析工具类
 */

public class DataParseUtil {

  private static final String TAG = "DataParseUtil";

  public static final GsonBuilder mGsonBuilder =
      new GsonBuilder().excludeFieldsWithoutExposeAnnotation();

  public static final Gson mGson = /*new Gson()*/ mGsonBuilder.create();

  /**
   * public static String toJson(Object object) {
   * return mGson.toJson(object);
   * }
   *
   * /**
   * 将JSON字符串转化成对象
   */
  public static <T> T fromJson(String json, Class<T> cls) {
    try {
      return mGson.fromJson(json, cls);
    } catch (JsonSyntaxException e) {
      Log.e(TAG, e.toString());
    }
    return null;
  }

  @Nullable public static List<String> parseListString(String json) {
    List<String> list = null;
    try {
      JSONArray array = new JSONArray(json);
      for (int i = 0; i < array.length(); i++) {

        if (list == null) list = new ArrayList<>();
        list.add(array.getString(i));
      }
    } catch (JSONException e) {
      Log.e(TAG, e.toString());
    }
    return list;
  }

  /**
   * 将字符串转化成对象集合
   *//*
  @Nullable public static <T> List<T> getListData(String json, Class<T> cls) {
    Type type = new TypeToken<ArrayList<JsonObject>>() {
    }.getType();
    ArrayList<T> arrayList = null;
    try {
      ArrayList<JsonObject> jsonObjects = mGson.fromJson(json, type);
      if (jsonObjects != null && jsonObjects.size() > 0) {
        arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
          arrayList.add(mGson.fromJson(jsonObject, cls));
        }
      }
    } catch (JsonSyntaxException e) {
      Log.e(TAG, e.toString());
    }
    return arrayList;
  }*/

  public static <T> List<T> getListData(String json, Class<T[]> clazz) {
    T[] ts = fromJson(json, clazz);
    if (ts != null && ts.length != 0) {
      ArrayList<T> list = new ArrayList<>();
      list.addAll(Arrays.asList(ts));
      return list;
    }
    return null;
  }
}
